package persistent;

import java.lang.reflect.InvocationTargetException;
import persistent.Exceptions.DriverConfigurationError;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class Mysql extends ManagerOnLSD {
	private String dbHost = "localhost";
	private String dbName = "BDReferencias";
	private String dbUser = null;
	private String dbPass = null;
	
	public Mysql() {
		try {
			this.loadConf();
		} catch (DriverConfigurationError e) {
			// sh...
		}
	}

	public Connection connect() {
		String url = this.getUrl();
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(this.getUrl(), this.dbUser, this.dbPass);
		} catch (ClassNotFoundException e) {
			System.out.println("Error de driver.");
			e.printStackTrace();
		} catch (SQLException e1) {
			System.out.println("Error de conexión.");
			e1.printStackTrace();
		}
		return connection;
	}

	// Carga la configuración para bases de datos MySQL
	private void loadConf() throws DriverConfigurationError {
		try {
			Class my = Class.forName("conf.Mysql");
			Object mysqlConf = null;
			try {
				mysqlConf = my.newInstance();
			} catch(InstantiationException e) {
				// pass
			}
			Class[] params = null;
			String confHost = my.getMethod("getHost", params).invoke(mysqlConf, params).toString();
			String confName = my.getMethod("getName", params).invoke(mysqlConf, params).toString();
			String confUser = my.getMethod("getUser", params).invoke(mysqlConf, params).toString();
			String confPass = my.getMethod("getPass", params).invoke(mysqlConf, params).toString();
			if(confHost != null) {
				this.dbHost = confHost;
			}
			if(confName != null) {
				this.dbName = confName;
			}
			if(confUser != null) {
				this.dbUser = confUser;
			}
			if(confPass != null) {
				this.dbPass = confPass;
			}
		} catch(IllegalAccessException e) {
			// return null;
		} catch(InvocationTargetException e) {
			// return null;
		} catch(NoSuchMethodException e) {
			// return null;
		} catch(ClassNotFoundException e) {
			// return null;
		}
        // return null;
	}	
	
	// Genera el string de conexión para cada base de datos
	public String getUrl() {
		return "jdbc:mysql://" + this.dbHost + "/" + this.dbName;
	}
}
